import React, {useContext} from 'react';
import {View, Image, Alert} from 'react-native';
import dayjs from 'dayjs';
import Toast from 'react-native-root-toast';
import {useNavigation} from '@react-navigation/native';
import {useMount, useSafeState} from 'ahooks';
import {Button, Text, ListItem} from '@rneui/base';
import {Dialog} from '@rneui/themed';
import {useSelector, useDispatch} from 'react-redux';
import GlobalContext from '@/GlobalContext';

import Datastore from 'react-native-local-mongodb';
import AsyncStorage from '@react-native-async-storage/async-storage';

const db = new Datastore({
  filename: 'localMongoDb001',
  storage: AsyncStorage,
  autoload: true,
});
db.ensureIndex(
  {fieldName: 'filePath', unique: true, sparse: true},
  function (err) {
    console.log('创建索引.err', err);
  },
);
// TTL索引，过期自动删除
// // Example of using expireAfterSeconds to remove documents 1 hour
// // after their creation (db's timestampData option is true here)
// db.ensureIndex({ fieldName: 'createdAt', expireAfterSeconds: 3600 }, function (err) {
// });

// // You can also use the option to set an expiration date like so
// db.ensureIndex({ fieldName: 'expirationDate', expireAfterSeconds: 0 }, function (err) {
//   // Now all documents will expire when system time reaches the date in their
//   // expirationDate field
// });
export default () => {
  const navigation = useNavigation();
  const dispatch = useDispatch();

  const [isVisible, setIsVisible] = useSafeState(false);

  const submit = async () => {
    try {
      // const doc = {today: new Date()};
      // await db.insert(doc, (err, newDoc) => {
      //   console.log('newDoc', newDoc);
      // });

      db.insert(
        [{filePath: 5}, {filePath: 42}, {filePath2: 5}],
        function (err, newDocs) {
          console.log('err', err);
          console.log('newDocs', newDocs);
        },
      );
    } catch (e) {}

    try {
      db.find({}, (err, docs) => {
        console.log('docs', docs);
      });
      db.count({}, function (err, count) {
        console.log('count', count);
      });
    } catch (e) {
      console.log('异常', e.message);
    }
  };
  return (
    <>
      <Button
        onPress={submit}
        containerStyle={{
          marginTop: 10,
        }}
        title="LocalMongoDb"
      />
      <Button
        onPress={() => {
          db.remove({}, {multi: true}, function (err, numRemoved) {
            console.log('numRemoved', numRemoved);
          });
          db.find({}, (err, docs) => {
            console.log('docs', docs);
          });
        }}
        containerStyle={{
          marginTop: 10,
        }}
        title="清空"
      />
    </>
  );
};
